//
//  EventDetailViewController.m
//  jungoo
//
//  Created by Sinbad Fly on 8/25/12.
//  Copyright (c) 2012 ABOM. All rights reserved.
//

#import "EventDetailViewController.h"
#import "Extensions.h"
#import "MyAnnotation.h"
#import <QuartzCore/QuartzCore.h>

@implementation EventDetailViewController

@synthesize event = _event, eventId = _eventId, delegate = _delegate;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    return self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)applyAppearance
{
    [self setLeftButtonImageActiveName:nil 
                          inactiveName:@"back-button" 
                                target:self 
                                action:@selector(back:)];
    [self setTitle:@"Event"];
    
    [self.tableView setBackgroundView:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"home_bg"]]];
    
    if (_event == nil && _eventId != nil) {
        [JGoUtility showProgressInView:self.view
                                target:self
                                 title:@"Loading..."
                              selector:@selector(delayLoadEvent:)];
    }
    
    if ([[_event objectForKey:@"Pending"] integerValue] == 1) {
        
        actionBottomView.frame = CGRectMake(0, 372, 320, 44);
        [self.view addSubview:actionBottomView];
        [self.tableView setContentInset:UIEdgeInsetsMake(0, 0, 44, 0)];
        
        [self setRightButtonImageActiveName:nil
                               inactiveName:@"report-button"
                                     target:self
                                     action:@selector(report:)];
    }
    else {
        [self setRightButtonImageActiveName:nil
                               inactiveName:@"delete-button"
                                     target:self
                                     action:@selector(delete:)];
    }
}

- (NSString*)eventTypeFromIndex:(NSInteger)index
{
    switch (index) {
        case 0:         
            return @"Social";
            break;            
        case 1:            
            return @"Career";
            break;            
        case 2:            
            return @"Education";
            break;            
    }
    
    return nil;
}

- (NSString*)realOnlineFromIndex:(NSInteger)index
{
    switch (index) {
        case 0:         
            return @"Real";
            break;            
        case 1:            
            return @"Online";
            break;         
    }
    
    return nil;
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self applyAppearance];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return NO;
}

- (void)dealloc
{
    [cell00 release];
    [cell01 release];
    [cell02 release];
    [cell03 release];
    [cell10 release];
    [cell11 release];
    [cell12 release];
    [cell20 release];
    [self setEvent:nil];
    
    [super dealloc];
}

#pragma mark - Action

- (void)back:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)report:(id)sender
{
    
}

- (void)delete:(id)sender
{
	[[[[UIAlertView alloc] initWithTitle: nil
								 message: @"Are you sure to delete the event?"
								delegate: (id)self
					   cancelButtonTitle: @"Yes"
					   otherButtonTitles: @"No", nil] autorelease] show];
}

- (IBAction)willGo:(id)sender
{
    MBProgressHUD *progress =    [JGoUtility showProgressInView:[JGoUtility frontFromView:self.view]
                                                         target:self
                                                          title:@"Processing..."
                                                       selector:@selector(delayEventUpdateStatus:)];
    
    progress.tag = 0;
}

- (IBAction)noGo:(id)sender
{
    MBProgressHUD *progress =    [JGoUtility showProgressInView:[JGoUtility frontFromView:self.view]
                                                         target:self
                                                          title:@"Processing..."
                                                       selector:@selector(delayEventUpdateStatus:)];
    
    progress.tag = 1;
}

#pragma mark - TableView Delegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (section) {
        case 0: {      
            return 4;
            break;
        }
        case 1: {
            return 3;
            break;
        }
        case 2: {
            return 1;
            break;
        }            
    }        

    return 0;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return (_event ? 3 : 0);
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{      
    switch (indexPath.section) {
        case 0: {      
            return 45;
            break;
        }
        case 1: {            
            switch (indexPath.row) {
                case 0: 
                    return 45;
                    break;
                case 1:       
                    return 55;
                    break;
                case 2:   
                    return 95;
                    break;
            }            
            break;
        }
        case 2: {
            return 47;
            break;
        }            
    }        
        
    return 44;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    
    switch (indexPath.section) {
        case 0: {      
            switch (indexPath.row) {
                case 0: {   
                    cell = cell00;
                    [cell titleTextWithTag:1].text = [_event objectForKey:@"event_title"];
                    break;
                }
                case 1: {   
                    cell = cell01;
                    [cell titleTextWithTag:1].text = [self eventTypeFromIndex:[[_event objectForKey:@"event_type"] integerValue]];
                    break;
                }
                case 2: {         
                    cell = cell02;
                    [cell titleTextWithTag:1].text = [_event objectForKey:@"circle_attending"];
                    break;
                }
                case 3: {         
                    cell = cell03;
                    [cell titleTextWithTag:1].text = [self realOnlineFromIndex:[[_event objectForKey:@"event_scope"] integerValue]];
                    break;
                }                    
            }  
            break;
        }
        case 1: {            
            switch (indexPath.row) {
                case 0: {   
                    cell = cell10;
                    NSDate *eventDate = [JGoUtility dateFromString1:[_event objectForKey:@"event_date"]];
                    NSString *dateString = [JGoUtility stringFromDate3:eventDate];            
                    NSString *eventTime = [NSString stringWithFormat:@"%@, %@ - %@",dateString,
                                 [JGoUtility longTimeToShortTime:[_event objectForKey:@"start_time"]],
                                 [JGoUtility longTimeToShortTime:[_event objectForKey:@"end_time"]]];
                    
                    [cell titleTextWithTag:1].text = eventTime;
                    break;
                }
                case 1: {    
                    cell = cell11;
                    [cell titleTextWithTag:1].text = [_event objectForKey:@"event_location"];
                    break;
                }
                case 2: {         
                    cell = cell12;
                    MKMapView* mapView = (id)[cell viewWithTag:1];                    
                    mapView.showsUserLocation = YES;
                    mapView.mapType=MKMapTypeStandard;	
                    mapView.layer.cornerRadius = 10.0;

                    MKCoordinateRegion region;
                    MKCoordinateSpan span;
                    span.latitudeDelta = 0.003;
                    span.longitudeDelta = 0.003;
                    CLLocationCoordinate2D location; 
                    if (![[_event objectForKey:@"event_lat"] isKindOfClass:[NSNull class]]) {
                        location.latitude = [[_event objectForKey:@"event_lat"] doubleValue];
                    }
                    if (![[_event objectForKey:@"event_lon"] isKindOfClass:[NSNull class]]) {
                        location.longitude = [[_event objectForKey:@"event_lon"] doubleValue];
                    }
                    
                    region.span = span;
                    region.center = location;
                    [mapView regionThatFits:region]; 
                    
                    CLLocationDegrees minLatitude = 90;
                    CLLocationDegrees maxLatitude = -90;
                    CLLocationDegrees minLongitude = 180;
                    CLLocationDegrees maxLongitude = -180;
                    
                    if (location.latitude > maxLatitude && location.latitude < minLatitude && location.longitude >maxLongitude && location.longitude < minLongitude ) {
                        [mapView setRegion:region animated:TRUE];
                    }
                    MyAnnotation *anno = [[MyAnnotation alloc] initWithCoords:location name:@""];
                    [mapView addAnnotation:anno];

                    break;
                }                    
            }            
            break;
        }
        case 2: {
            cell = cell20;
            [cell titleTextWithTag:1].text = [_event objectForKey:@"event_description"];
        }            
    }        
    
    if ([[cell titleTextWithTag:1] respondsToSelector:@selector(font)]) {
        [cell titleTextWithTag:1].font = JGO_FONT_HELVETICA_B(14);
    }
    
    return cell;
}

- (void)delayLoadEvent:(MBProgressHUD*)progress
{
    NSDictionary *user = [JGoUtility sharedCreateAccount];
    NSString *userId = [user objectForKey:@"user_id"];
    NSError *error = nil;
    
    NSDictionary *aEvent = [JGoAPI getEventDetailWithUserId:userId eventId:_eventId error:&error ];
    
    if (!error) {
        self.event = aEvent;
        [self.tableView reloadData];
    }
    else {
        [JGoUtility showAlert:[error localizedDescription]];
    }
    
    [progress hide:YES];
}

- (void)delayEventUpdateStatus:(MBProgressHUD*)progress
{
    NSString *status = [NSString stringWithFormat:@"%d",progress.tag];
    NSString *userId = [[JGoUtility sharedCreateAccount] objectForKey:@"user_id"];
    NSString *eventId = [_event objectForKey:@"event_id"];
    NSError *error = nil;
    
    [JGoAPI updateEventStatusWithUserId:userId
                                eventId:eventId status:status
                                  error:&error];
    
    if (error) {
        [JGoUtility showAlert:[error localizedDescription]];
        
    }
    else {
       [_eventId setValue:nil forKey:@"Pending"];
    }
    
    if (!error) {
        
        if ([_delegate respondsToSelector:@selector(eventDetailViewController:event:isDeleted:)]) {
            [_delegate eventDetailViewController:self event:_event isDeleted:(progress.tag == 1 ? YES : NO)];
        }
        [self.navigationController popViewControllerAnimated:YES];
    }
    
    [progress hide:YES];
}

- (void)delayEventDelete:(MBProgressHUD*)progress
{
    NSString *userId = [[JGoUtility sharedCreateAccount] objectForKey:@"user_id"];
    NSString *eventId = [_event objectForKey:@"event_id"];
    NSError *error = nil;
    
    [JGoAPI deleteEventsWithUserId:userId eventIds:eventId error:&error];
    
    if (error) {
        [JGoUtility showAlert:[error localizedDescription]];
    }
    else {
        
        if ([_delegate respondsToSelector:@selector(eventDetailViewController:event:isDeleted:)]) {
            [_delegate eventDetailViewController:self event:_event isDeleted:YES];
        }
        [self.navigationController popViewControllerAnimated:YES];
    }
    
    [progress hide:YES];
}

#pragma mark - Alert Delegate

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [JGoUtility showProgressInView:[JGoUtility frontFromView:self.view]
                                target:self
                                 title:@"Deleting..."
                              selector:@selector(delayEventDelete:)];
    }
}


@end
